<template>
  <a-form
    :model="userForm"
    name="userForm"
    :label-col="{ span: 6 }"
    :wrapper-col="{ span: 12 }"
    autocomplete="off"
    @finish="onFinish"
    @finishFailed="onFinishFailed"
  >
    <a-form-item label="用户名" name="username">
      <a-input v-model:value="userForm.account" disabled />
    </a-form-item>

    <a-form-item
      label="姓名"
      name="nickname"
      :rules="[{ required: true, message: '请输入用户名!' }]"
    >
      <a-input v-model:value="userForm.name" />
    </a-form-item>

    <a-form-item label="用户头像">
      <a-upload
        v-model:file-list="fileList"
        name="avatar"
        list-type="picture-card"
        class="avatar-uploader"
        :show-upload-list="false"
        :customRequest="handleUpload"
      >
        <img v-if="imageUrl" :src="imageUrl" alt="avatar" class="avatar" />
        <div v-else>
          <LoadingOutlined v-if="loading" />
          <PlusOutlined v-else />
          <div class="ant-upload-text">上传</div>
        </div>
      </a-upload>
    </a-form-item>
    <a-form-item :wrapper-col="{ offset: 6, span: 18 }">
      <a-button type="primary" html-type="submit" :loading="submitting.value">提交</a-button>
      <a-button @click="handleReset" style="margin-left: 8px">重置</a-button>
    </a-form-item>
  </a-form>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { fetchUserInfo } from '@/api/system/user';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { uploadFile } from '@/api/upload';
import {message} from 'ant-design-vue';

const loading = ref(false);
const submitting = ref(false);
const imageUrl = ref(''); // 预览图像的URL

const userForm = reactive({
  account: '',
  name: '', // 可编辑
  avatar: '' // 用户头像
});

onMounted(async () => {
  loading.value = true;
  try {
    const data = await fetchUserInfo();
    userForm.account = data.data.account;
    userForm.name = data.data.name;
    userForm.avatar = data.data.avatar;
    imageUrl.value = data.data.avatar; // 设置头像的初始预览
  } catch (error) {
    console.error('Failed to fetch user info:', error);
  } finally {
    loading.value = false;
  }
});
// 保存用户选择的文件对象
const avatarFile = ref(null);

// 文件选择和预览
const handleFileChange = (file) => {
  avatarFile.value = file; // 保存文件对象
  const reader = new FileReader();
  reader.onload = e => {
    imageUrl.value = e.target.result; // 设置预览图像
  };
  reader.readAsDataURL(file); // 读取文件作为URL
  // 阻止自动上传，因为我们使用的是自定义上传
  return false;
};

// 文件上传
// 文件上传
const handleUpload = async () => {
  if (!avatarFile.value) {
    // 如果没有选择文件，直接返回
    return;
  }

  const formData = new FormData();
  formData.append('file', avatarFile.value); // 使用保存的文件对象

  loading.value = true;
  try {
    const response = await uploadFile(formData); // 上传文件
    if (response.code === 1) {
      // 上传成功
      imageUrl.value = response.data[0]; // 更新 imageUrl
      userForm.avatar = response.data[0]; // 更新 userForm 的 avatar 字段
      message.success('文件上传成功。');
    } else {
      throw new Error(response.msg || '上传失败');
    }
  } catch (error) {
    message.error(`文件上传失败。${error.message || ''}`);
  } finally {
    loading.value = false;
  }
};


// 表单提交
const onFinish = async () => {
  // 在这里调用 handleUpload 函数来上传头像
  await handleUpload();
  submitting.value = true;
  try {
    // 这里应该有一个API请求来更新用户信息，包括新的头像URL
    console.log('Submitted:', userForm);
    // 假设更新成功后，response包含了更新后的用户信息
  } catch (error) {
    console.error('Update failed:', error);
  } finally {
    submitting.value = false;
  }
};

// 表单提交失败
const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo);
};

// 重置表单项
const handleReset = () => {
  userForm.name = '';
  imageUrl.value = userForm.avatar; // 重置头像预览
};

</script>

<style scoped>
/* 样式留空 */
</style>
